import requests
import ssl
import asyncio
from spider.config.config import url_config
from spider.decorator import need_login
from spider.utils.BaseRequest import BaseRequest
from spider.utils.Looper import Looper

ssl._create_default_https_context = ssl._create_unverified_context

# 禁用安全请求警告
requests.packages.urllib3.disable_warnings()


class WeiboSpider(BaseRequest):
    def __init__(self):
        super().__init__()
        self.user_id = None
        self.looper = Looper()
        self.searchMap = dict()

    def login_weibo(self):
        if self.user_id is None:
            url_obj = url_config.get_login_url()
            resp = self.send_request(url_obj)
            result = resp.json()
            self.user_id = result['data']['uid']

    @need_login
    def search_user(self, keyword):
        url_obj = url_config.get_search_url(keyword)
        resp = self.send_request(url_obj)
        result = None
        if resp.status_code == 200:
            result = resp.json()
            if result['ok'] == 1:
                result = result['data']

        return self.get_search_users(result)
        uid = self.get_search_user_id(result, keyword)
        print('uid', uid)
        container_id = self.get_home_container_id(uid)
        print('container_id', container_id)
        self.get_all_blog(container_id)

    def get_home_container_id(self, uid):
        url_obj = url_config.get_home_container_id_url(uid)
        resp = self.send_request(url_obj)
        result = resp.json()
        container_id = None
        tabs = []
        if result.get('ok', None) == 1:
            tabs = result['data']['tabsInfo']['tabs']
        for tab in tabs:
            if tab['tab_type'] == 'weibo':
                container_id = tab['containerid']
                break
        return container_id

    @staticmethod
    def get_search_users(search_result):
        cards = search_result.get('cards', [])
        match_user = None
        users = []
        for card in cards:
            if card['card_type'] == 11:
                users = card['card_group']
        return [_.get('user', None) for _ in users]
        
    @staticmethod
    def get_search_user_id(search_result, keyword):
        cards = search_result['cards']
        match_user = None
        users = []
        for card in cards:
            if card['card_type'] == 11:
                users = card['card_group']
        for user in users:
            if user['card_type'] == 10 and user['user'] and user['user']['screen_name'] == keyword:
                match_user = user['user']
                break
        return match_user and match_user['id']

    def get_all_blog(self, cid):
        return
        get_number_future = asyncio.ensure_future(self.get_blog_list_by_page(cid, 1))
        self.looper.run(get_number_future)
        result_number = get_number_future.result()
        page_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        tasks = [asyncio.ensure_future(self.get_blog_list_by_page(cid, _)) for _ in page_arr]
        try:
            self.looper.run(asyncio.wait(tasks))
            result_arr = [_.result() for _ in tasks]
            print(result_arr)
        except Exception:
            print('exit', Exception.__str__())
        # cor = self.get_blog_list_by_page(cid, 1)
        # future = asyncio.ensure_future(cor)
        # self.looper.run(future)
        # print(future.result())

    async def get_blog_list_by_page(self, cid, page):
        result = await self.looper.loop.run_in_executor(None, self.get_page_blog_fn, cid, page)
        return result

    def get_page_blog_fn(self, cid, page):
        url_obj = url_config.get_blogs_url(cid, page)
        resp = self.send_request(url_obj)
        return resp.json().get('ok')

    def get_blog_number(self):
        pass





